#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/3 21:13
# @Author  : huidong.bai
# @File    : SerialReader.py
# @Software: PyCharm

import os
from threading import Thread, Timer
import time
import serial
import serial.tools.list_ports
import platform


def get_serial_com():
    if platform.system() == 'Windows':
        port_list = list(serial.tools.list_ports.comports())
        port_list_name = []
        if len(port_list) <= 0:
            print("串口设备为空，请检查!")
        else:
            for each_port in port_list:
                port_list_name.append(each_port[0])
        return port_list_name[0]
    else:
        return os.popen('ls /dev/tty.*usbserial*').readline().strip()


def get_serial(com_port):
    # 打开串口，并得到串口对象
    ser = serial.Serial(com_port, '115200', timeout=4)
    # 判断是否打开成功
    if not ser.is_open:
        ser = -1
        print('打开串口失败')
        return ser
    return ser


def write_log(ser):
    # 获取日志重定向位置，在桌面下创建logs文件夹，日志将存在该文件夹下
    desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
    file_path = os.path.join(desktop_path, 'logs')
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    ex_time = time.strftime('%Y-%m-%d-%H-%M', time.localtime(time.time()))
    log_path = os.path.join(file_path, 'pycharm_logs', f'rtos_log_{ex_time}.log')

    print(log_path)

    with open(log_path, 'a+', encoding='UTF-8') as fp:
        while True:
            line = ser.readline().strip()
            log = line.replace(b'\\\\x', b'%').decode("UTF-8", "ignore")
            if len(log):
                fp.write(log + '\r\n')
                print(log)


def execute(ser):
    # cmd = 'ps\n'
    cmd = 'free\n'
    ser.write(cmd.encode())
    timer = Timer(15, execute, args=(serial,))
    timer.start()


if __name__ == '__main__':
    com = get_serial_com()
    serial = get_serial(com)
    execute(serial)
    t = Thread(target=write_log, args=(serial,))
    t.start()
